package mission_tour.solution;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.widget.Toast;

public class tour_loading extends Activity implements ServerIp{
    /** Called when the activity is first created. */
	String phonenumber ="";
	AlertDialog.Builder nologin;
	LocationManager lm = null;
	ComponentName tService;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tour_loding);
        
        items.coupon_list.removeAll(items.coupon_list);
        items.event_position_list.removeAll(items.event_position_list);
        items.event_info_list.removeAll(items.event_info_list);
        items.event_list.removeAll(items.event_list);
        items.map_position_list.removeAll(items.map_position_list);
    	
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);	//GPS활성화 확인
        if(!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            createGpsDisabledAlert();
        }else{
        	final ProgressDialog nowloding = ProgressDialog.show(tour_loading.this,"","서버에 접속 하고 있습니다....",true);
        	
            SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
    		
            phonenumber = pref.getString("phone", "");
            
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        	NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        	final boolean isWifiConn = ni.isConnected();
        	ni = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        	final boolean isMobileConn = ni.isConnected();
        		            		  
        	if(isWifiConn==false && isMobileConn==false){
        		//인터넷에 연결할 수 없습니다. 연결을 확인하세요.
        		nowloding.cancel();
        		nologin = new AlertDialog.Builder(this);
    			nologin.setTitle(items.appname);
    			nologin.setMessage("서버에 접속이 되지 않습니다\n무선네트워크 접속을 확인해 주신 후 다시 시도 해 주세요");
    			nologin.setIcon(R.drawable.icon);
    			nologin.setPositiveButton("확 인", new DialogInterface.OnClickListener(){
    				@Override
    				public void onClick(DialogInterface dialog, int which) {
    					// TODO Auto-generated method stub
    					moveTaskToBack(true);
    					android.os.Process.killProcess(android.os.Process.myPid());
    				}
    			});
    			nologin.show();

    		}else{
    			new Thread(new Runnable() {    
    				@Override
    				public void run() {
    					URL urll = null;
    			        
    			        try {
    			        	
    			        	urll = new URL(event_position_list+"?app_type="+items.apptype);
    			        	
    				        HttpURLConnection httpl = (HttpURLConnection)urll.openConnection();  
    				
    						BufferedReader inl = new BufferedReader(new InputStreamReader(httpl.getInputStream()));  
    						StringBuffer bufferl = new StringBuffer();
    						 
    						int l;  
    						 
    						while((l=inl.read()) != -1){
    							bufferl.append((char)l);
    						}
    						
    						String resultlist = bufferl.toString().trim();
    						
    						XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
    						factory.setNamespaceAware(true);
      
    						boolean tagok = false;
      
    						String[] position_call = null;
      
    						XmlPullParser xpp = factory.newPullParser();
    						xpp.setInput(new StringReader(resultlist));
      
    						int eventType = xpp.getEventType();
      
    						while (eventType != XmlPullParser.END_DOCUMENT) {
    							if(eventType == XmlPullParser.START_DOCUMENT) {
    								System.out.println("Start document");
    							}

    							if (eventType == XmlPullParser.END_DOCUMENT) {
    								System.out.println("End document");
    							}

    							if (eventType == XmlPullParser.START_TAG) {
    	
    								if(xpp.getName().equals("name")){
    									tagok = true;
    								}
    							}

    							if (eventType == XmlPullParser.END_TAG) {
    							}

    							if (eventType == XmlPullParser.TEXT) {
    								if(tagok){
    									position_call = xpp.getText().split(",");
    								}
    								events evs = new events(Integer.parseInt(position_call[0]),position_call[1],Double.parseDouble(position_call[2]),Double.parseDouble(position_call[3]),Double.parseDouble(position_call[4]),Double.parseDouble(position_call[5]));
    								
    					      		items.event_position_list.add(evs);
    							}
    							eventType = xpp.next();
    						}
    						
						  	
    						urll = new URL(tour_map_position_call+"?app_type="+items.apptype+"&c_code="+items.c_code);
								
							httpl = (HttpURLConnection)urll.openConnection();  
						
							inl = new BufferedReader(new InputStreamReader(httpl.getInputStream()));  
							bufferl = new StringBuffer();
								 
							int c;  
								 
							while((c=inl.read()) != -1){
								bufferl.append((char)c);
							}
								
							resultlist= bufferl.toString().trim();
							
							factory = XmlPullParserFactory.newInstance();
							factory.setNamespaceAware(true);
								  
							tagok = false;
								  
							String[] map_position_call = null;
								  
							xpp = factory.newPullParser();
							xpp.setInput(new StringReader(resultlist));
								  
							eventType = xpp.getEventType();
								  
							while (eventType != XmlPullParser.END_DOCUMENT) {
								      
								if(eventType == XmlPullParser.START_DOCUMENT) {
									System.out.println("Start document");
								}
								
								if (eventType == XmlPullParser.END_DOCUMENT) {
									System.out.println("End document");
								}
								
								if (eventType == XmlPullParser.START_TAG) {
									
									if(xpp.getName().equals("name")){
										tagok = true;
									}
								}
								
								if (eventType == XmlPullParser.END_TAG) {
								}
								
								if (eventType == XmlPullParser.TEXT) {
									if(tagok){
										map_position_call = xpp.getText().split("@");
									}
									map_positions mp = new map_positions(Integer.parseInt(map_position_call[0]),Double.parseDouble(map_position_call[1]),Double.parseDouble(map_position_call[2]));
											
									items.map_position_list.add(mp);
								}
								eventType = xpp.next();
							}		
    			        } catch (MalformedURLException e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    			        } catch (Exception e) {
    						// TODO Auto-generated catch block
    						runOnUiThread(new Runnable(){
    				            @Override
    				             public void run() {
    				            	nologin = new AlertDialog.Builder(tour_loading.this);
    				    			nologin.setTitle(items.appname);
    				    			nologin.setMessage("서버에 접속이 되지 않습니다\n잠시 후 다시 시도해 주세요");
    				    			nologin.setIcon(R.drawable.icon);
    				    			nologin.setPositiveButton("확 인", new DialogInterface.OnClickListener(){
    				    				@Override
    				    				public void onClick(DialogInterface dialog, int which) {
    				    					// TODO Auto-generated method stub
    				    					moveTaskToBack(true);
    				    					android.os.Process.killProcess(android.os.Process.myPid());
    				    				}
    				    			});
    				    			nologin.show();
    				             }
    				        });
    						e.printStackTrace();
    					}
    				}
    		    }).start();
    			
    			if(phonenumber.equals("")){
    				nowloding.cancel();
    				Intent intent = new Intent(tour_loading.this, tour_login.class);
    				startActivityForResult(intent, 0);
    				finish();
    			}else{
    				new Thread(new Runnable() {    
    					@Override
    					public void run() {
    						URL url = null;
    				        
    				        try {
    				        	
    				        	url = new URL(ulogin+"?mobile_num="+phonenumber);
    				        	
    					        HttpURLConnection http = (HttpURLConnection)url.openConnection();  
    					
    							BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream()));  
    							StringBuffer buffer = new StringBuffer();
    							 
    							int z;  
    							 
    							while((z=in.read()) != -1){
    								buffer.append((char)z);
    							}
    							
    							String[] result = buffer.toString().trim().split(",");
    							
    							if(result[0].equals("1")){
    								nowloding.cancel();
    								
    								items.c_code = Integer.parseInt(result[1]);
    								items.c_sex = Integer.parseInt(result[2]);
    								items.c_point = Integer.parseInt(result[3]);
    								
    								Intent intent = new Intent(tour_loading.this, tour_infomation_page.class);
    								startActivityForResult(intent, 0);
    								finish();
    							}else{
    								Intent intent = new Intent(tour_loading.this, tour_login.class);
    								startActivityForResult(intent, 0);
    								finish();
    							}
    				        } catch (MalformedURLException e) {
    							// TODO Auto-generated catch block
    							e.printStackTrace();
    						} catch (IOException e) {
    							// TODO Auto-generated catch block
    							runOnUiThread(new Runnable(){
    					            @Override
    					             public void run() {
    					            	nologin = new AlertDialog.Builder(tour_loading.this);
    					    			nologin.setTitle(items.appname);
    					    			nologin.setMessage("서버에 접속이 되지 않습니다\n잠시 후 다시 시도해 주세요");
    					    			nologin.setIcon(R.drawable.icon);
    					    			nologin.setPositiveButton("확 인", new DialogInterface.OnClickListener(){
    					    				@Override
    					    				public void onClick(DialogInterface dialog, int which) {
    					    					// TODO Auto-generated method stub
    					    					moveTaskToBack(true);
    					    					android.os.Process.killProcess(android.os.Process.myPid());
    					    				}
    					    			});
    					    			nologin.show();
    					             }
    					        });
    							e.printStackTrace();
    						}
    					}
    			    }).start();
    			}
    		}
        }
    }
    
    private void createGpsDisabledAlert() {	//gps 안켜졌을 경우 호출 알럿 창
	    AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    builder.setMessage("GPS가 비활성화 되어 있습니다.\nGPS를 활성화 하시겠습니까?\n\n- 무선네트워크 사용 항목은 체크하지 말아주세요 -");
	    builder.setCancelable(false);
	    builder.setTitle(items.appname);
	    builder.setIcon(R.drawable.icon);
	    builder.setPositiveButton("네",
	                    new DialogInterface.OnClickListener() {
	                        public void onClick(DialogInterface dialog, int id) {
	                            showGpsOptions();
	                        }
	                })
	            .setNegativeButton("아니오",
	                    new DialogInterface.OnClickListener() {
	                        public void onClick(DialogInterface dialog, int id) {
	                        	moveTaskToBack(true);
		    					android.os.Process.killProcess(android.os.Process.myPid());
	                        }
	                });
	    AlertDialog alert = builder.create();
	    alert.show();
	}
    
    private void showGpsOptions() {
	    Intent gpsOptionsIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
	    startActivity(gpsOptionsIntent);
	    Toast.makeText(tour_loading.this,"설정 완료 후 어플을 다시 실행 하여 주세요",Toast.LENGTH_SHORT).show();
	}
    
}
